import React from 'react';
import './index.css';
import Tool from  'tool/tool.jsx';
import User from  'service/user-service.jsx';
const _req = new Tool();
const _user = new User();

class Login extends React.Component{
  constructor(props){
    super(props);
    this.state={
      username:'admin',
      password:'admin',
      redirect:_req.getUrlParam('redirect') || '/'
    };
    this.onLogin = this.onLogin.bind(this);
  }
    //回车登录
    onInputKeyUp(e){
      if(e.keyCode === 13){   
        //调用类的成员函数，需要绑定this，指向当前类; 或直接使用箭头函数
        this.onLogin();
      }
    }
   //修改浏览器中的标签名
   componentDidMount(){
    document.title='登录-HOUSYSTEM' ;
  }
  //当输入改变
  onInputChange(e){
   let inputname =e.target.name,
       inputvalue=e.target.value;
   this.setState({
     [inputname]:inputvalue
   })
  };
  //点击提交表单
  onLogin(){
    let loginInfo ={
      username: this.state.username,
      password: this.state.password
    };
   let  checkResult =_user.checkInfo(loginInfo);
     if(checkResult.status){
            _user.login(loginInfo).then((res)=>{
              //将登陆信息存入localStorage中
              _req.setLocalStorage('userInfo',res);
              //请求成功就从登录页返回上级页面
              this.props.history.push(this.state.redirect);
            },(errMsg)=>{
              _req.errorTips(errMsg);
            });
     }else{
            _req.errorTips(checkResult.msg);
      }
  }
  render(){
    return(
        <div className="col-md-4 col-md-offset-4">
          <div className="panel panel-default login-panel">
              <div className="panel-heading">欢迎使用 HouSystem管理系统</div>
              <div className="panel-body">
                  <div>
                    <div className="form-group">
                      <input type="text"
                             value={this.state.username}
                             name="username"
                             className="form-control" 
                             placeholder="请输入用户名:"
                             onKeyUp ={e=>{this.onInputKeyUp(e)}}
                             onChange={e=>this.onInputChange(e)}/>
                    </div>
                    <div className="form-group">
                      <input  type="password"
                              value={this.state.password}
                              name="password"
                              className="form-control" 
                              placeholder="请输入密码："
                              onKeyUp ={e=>{this.onInputKeyUp(e)}}
                              onChange={e=>this.onInputChange(e)}/>
                    </div>
                    <button className="btn btn-primary btn-lg btn-block"
                            onClick={(e)=>this.onLogin(e)}>
                            登录
                    </button>
                  </div >
              </div>
            </div>
        </div>  
    );
  }
}
export default Login;